package com.api.shuigui.service.impl;

import com.api.shuigui.service.ModelDataService;
import com.api.shuigui.utils.DocUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.general.MD5;
import weaver.general.Util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 泛微-何汶俊
 * @date 2022-11-30 21:27
 */
public class ModelDataServiceImpl implements ModelDataService {

    private static final Logger LOGGER = LoggerFactory.getLogger("ModelDataServiceImpl");

    @Override
    public Map<String, Object> getData(Map<String, Object> params) {
        //模块id
        String type = Util.null2String(params.get("type"));
        int num = Util.getIntValue(Util.null2String(params.get("num")), 0);
        if ("".equals(type)) {
            return new HashMap<>();
        }
        switch (type) {
            case "banner":
                //获得首页轮播图数据
                return getBannerData(num);
            case "Leader":
                //获得领导班子数据
                return getLeaderData(num);
            case "link":
                return getLinkData(num);
            case "business":
                return getBusinessData(num);
            case "honor":
                return getHonorData(num);
            case "org":
                return getOrgData(num);
            default:
                return new HashMap<>();
        }
    }

    /**
     * 获得学术组织数据
     *
     * @param num 数量，0为全部
     * @return 学术组织数据
     */
    private Map<String, Object> getOrgData(int num) {
        //初始化返回
        Map<String, Object> result = new HashMap<>();
        //初始化数据库连接
        RecordSet set = new RecordSet();
        //得到数据库类型
        String dbType = set.getDBType();
        //初始化sql
        String sql = "select fl,zzmc,zzlj from uf_xszzwh";
        if (num > 0) {
            if ("oracle".equals(dbType)) {
                sql += " where rownum <= " + num;
            } else if ("sqlserver".equals(dbType)) {
                sql = "select top " + num + " fl,zzmc,zzlj from uf_xszzwh";
            } else if ("mysql".equals(dbType)) {
                sql += " limit " + num;
            }
        }
        //执行sql
        boolean b = set.executeQuery(sql);
        if (b) {
            List<Map<String, Object>> associationList = new ArrayList<>();
            List<Map<String, Object>> placeList = new ArrayList<>();
            while (set.next()) {
                Map<String, Object> map = new HashMap<>();
                int fl = Util.getIntValue(set.getString("fl"), 0);
                map.put("zzmc", Util.null2String(set.getString("zzmc")));
                map.put("zzlj", Util.null2String(set.getString("zzlj")));
                if (fl == 0) {
                    associationList.add(map);
                } else {
                    placeList.add(map);
                }
            }
            result.put("xhData", associationList);
            result.put("dfData", placeList);
        }
        return result;
    }

    /**
     * 获得荣誉证书数据
     *
     * @param num 数量，0为全部
     * @return 数据集
     */
    private Map<String, Object> getHonorData(int num) {
        //初始化返回
        Map<String, Object> result = new HashMap<>();
        //初始化数据库连接
        RecordSet set = new RecordSet();
        //得到数据库类型
        String dbType = set.getDBType();
        //初始化sql
        String sql = "select rymc,ryzs from uf_zyrywh";
        if (num > 0) {
            if ("oracle".equals(dbType)) {
                sql += " where rownum <= " + num;
            } else if ("sqlserver".equals(dbType)) {
                sql = "select top " + num + " rymc,ryzs from uf_zyrywh";
            } else if ("mysql".equals(dbType)) {
                sql += " limit " + num;
            }
        }
        //执行sql
        boolean b = set.executeQuery(sql);
        if (b) {
            List<Map<String, Object>> honorList = new ArrayList<>();
            while (set.next()) {
                Map<String, Object> map = new HashMap<>();
                //名称
                map.put("name", Util.null2String(set.getString("rymc")));
                //图片docId
                String docIds = Util.null2String(set.getString("ryzs"));
                //可能有多个图片，只取第一个
                String docId = docIds.split(",")[0];
                //图片
                map.put("img", getImgUrlByDocId(docId, "honor"));
                honorList.add(map);
            }
            result.put("data", honorList);
        }
        return result;
    }

    /**
     * 获得业务范围数据
     *
     * @param num 数量，0为全部
     * @return 数据集
     */
    private Map<String, Object> getBusinessData(int num) {
        //初始化返回
        Map<String, Object> result = new HashMap<>();
        //初始化数据库连接
        RecordSet set = new RecordSet();
        //得到数据库类型
        String dbType = set.getDBType();
        //初始化sql
        String sql = "select ywmc,ms from uf_ywfw";
        if (num > 0) {
            if ("oracle".equals(dbType)) {
                sql += " where rownum <= " + num;
            } else if ("sqlserver".equals(dbType)) {
                sql = "select top " + num + " ywmc,ms from uf_ywfw";
            } else if ("mysql".equals(dbType)) {
                sql += " limit " + num;
            }
        }
        //执行sql
        boolean b = set.executeQuery(sql);
        if (b) {
            List<Map<String, Object>> businessList = new ArrayList<>();
            while (set.next()) {
                Map<String, Object> map = new HashMap<>();
                //名称
                map.put("name", Util.null2String(set.getString("ywmc")));
                //描述
                map.put("desc", Util.null2String(set.getString("ms")));
                businessList.add(map);
            }
            result.put("data", businessList);
        }
        return result;
    }

    /**
     * 友情链接数据
     *
     * @param num 数量，0为全部
     * @return 数据集
     */
    private Map<String, Object> getLinkData(int num) {
        //初始化返回
        Map<String, Object> result = new HashMap<>();
        //初始化数据库连接
        RecordSet set = new RecordSet();
        //得到数据库类型
        String dbType = set.getDBType();
        //初始化sql
        String sql = "select id,fl,ljmc,ljdz from uf_yqljwh";
        if (num > 0) {
            if ("oracle".equals(dbType)) {
                //sql += " where rownum <= " + num;
                 sql += " where rownum <= " + num + " order by px";
            } else if ("sqlserver".equals(dbType)) {
                //sql = "select top " + num + " id,fl,ljmc,ljdz from uf_yqljwh";
                sql = "select top " + num + " id,fl,ljmc,ljdz,px from uf_yqljwh order by px";
            } else if ("mysql".equals(dbType)) {
                //sql += " limit " + num;
                sql += " limit " + num + " order by px";
            }
        } else {
            sql += " order by px";
        }
        //执行sql
        boolean b = set.executeQuery(sql);
        if (b) {
            Map<String, List<Map<String, Object>>> linkData = new HashMap<>();
            while (set.next()) {
                Map<String, Object> map = new HashMap<>();
                //id
                map.put("value", Util.getIntValue(set.getString("id")));
                //名称
                map.put("label", Util.null2String(set.getString("ljmc")));
                //地址
                map.put("url", Util.null2String(set.getString("ljdz")));
                //类型
                String fl = Util.null2String(set.getString("fl"));
                //从Map中得到该分类的数据集，如果未初始化进行初始化
                List<Map<String, Object>> flData = linkData.computeIfAbsent(fl, k -> new ArrayList<>());
                flData.add(map);
            }
            result.put("data", linkData);
        }
        return result;
    }

    /**
     * 获得领导数据
     *
     * @param num 数量，0为全部
     * @return 数据集
     */
    private Map<String, Object> getLeaderData(int num) {
        //初始化返回
        Map<String, Object> result = new HashMap<>();
        //初始化数据库连接
        RecordSet set = new RecordSet();
        //得到数据库类型
        String dbType = set.getDBType();
        //初始化sql
        String sql = "select xm,zp,ll from uf_yldwh";
        if (num > 0) {
            if ("oracle".equals(dbType)) {
                sql += " where rownum <= " + num;
            } else if ("sqlserver".equals(dbType)) {
                sql = "select top " + num + " xm,zp,ll from uf_yldwh";
            } else if ("mysql".equals(dbType)) {
                sql += " limit " + num;
            }
        }
        //初始化数据集合
        List<Map<String, Object>> dataList = new ArrayList<>();
        //执行sql
        boolean b = set.executeQuery(sql);
        while (b && set.next()) {
            //初始化数据
            Map<String, Object> data = new HashMap<>();
            data.put("name", set.getString("xm"));
            String docIds = Util.null2String(set.getString("zp"));
            //单张图片docId
            String docId = docIds.split(",")[0];
            //根据docId得到图片链接
            data.put("img", getImgUrlByDocId(docId, "leader"));
            data.put("ll", set.getString("ll"));
            dataList.add(data);
        }
        result.put("data", dataList);
        return result;
    }

    /**
     * 获得首页banner数据
     *
     * @param num 数量，0为全部
     * @return 首页banner数据
     */
    private Map<String, Object> getBannerData(int num) {
        //初始化返回
        Map<String, Object> result = new HashMap<>();
        //初始化数据库连接
        RecordSet set = new RecordSet();
        //得到数据库类型
        String dbType = set.getDBType();
        //初始化sql
        String sql = "select biaoti,tp,ljdz,sfzd,show_status from uf_sylbt order by sfzd,modedatacreatedate desc,modedatacreatetime desc";
        if (num > 0) {
            if ("oracle".equals(dbType)) {
                //oracle数据库
                sql = "select biaoti,tp,ljdz,sfzd,show_status from uf_sylbt where rownum <= " + num + " order by sfzd,modedatacreatedate desc,modedatacreatetime desc";
            } else if ("sqlserver".equals(dbType)) {
                //sqlserver数据库
                sql = "select top " + num + " biaoti,tp,ljdz,sfzd,show_status from uf_sylbt";
            } else if ("mysql".equals(dbType)) {
                //mysql数据库
                sql += " limit " + num;
            }
        }
        LOGGER.info("getBannerData execute sql {}",sql);
        //初始化数据集合
        List<Map<String, Object>> dataList = new ArrayList<>();
        //执行sql
        boolean b = set.executeQuery(sql);
        result.put("top", false);
        //遍历结果
        while (b && set.next()) {
            //初始化banner
            Map<String, Object> banner = new HashMap<>();
            //标题
            banner.put("title", set.getString("biaoti"));
            //图片,可能会有多张图片，只取第一张
            String docIds = Util.null2String(set.getString("tp"));
            //单张图片docId
            String docId = docIds.split(",")[0];
            //根据docId得到图片链接
            banner.put("img", getImgUrlByDocId(docId, "banner"));
            //链接地址
            banner.put("url", set.getString("ljdz"));
            banner.put("show_status", set.getString("show_status"));
            int sfzd = set.getInt("sfzd");
            if (sfzd == 0) {
                result.put("top", true);
            }
            //添加到数据集中
            dataList.add(banner);
        }
        result.put("data", dataList);
        return result;
    }

    private String getImgUrlByDocId(String docId, String type) {
        //初始化数据库连接
        RecordSet set = new RecordSet();
        //初始化sql
        String sql = "select d.imagefilename,i.filerealpath from DocImageFile d left join ImageFile i on i.imagefileid = d.imagefileid where d.docid = " + docId;
        //执行sql
        boolean b = set.executeQuery(sql);
        LOGGER.info("getImgUrlByDocId execute sql {}",sql);
        //得到结果
        if (b && set.next()) {
            //图片名称
            String fileName = set.getString("imagefilename");
            //图片路径
            String filePath = set.getString("filerealpath");
            //文件类型
            String fileType = com.wbi.util.Util.null2String(fileName.substring(fileName.lastIndexOf(".") + 1));
            //图片转存位置
            String savePath = "interface/imgs/" + type + "/" + docId + "/";
            //图片转存名称
            String saveName = docId + "_" + new MD5().getMD5ofStr(fileName) + "." + fileType;
            //判断图片是否存在
            if (DocUtil.isCategoryByName(saveName, filePath)) {
                String path = "/" + savePath + saveName;

                LOGGER.info("getImgUrlByDocId exist {}",path);
                //图片存在直接返回图片链接
                return path;
            }
            //图片链接
            try {
                LOGGER.info("getImgUrlByDocId unExist");
                return DocUtil.readZipFile(filePath, fileName, saveName, savePath);
            } catch (IOException e) {
                return "";
            }
        }
        return "";
    }


}
